package com.iqiyi.pps.epg.core.rpc.qipu.impl;

import com.alibaba.fastjson.JSON;
import com.google.protobuf.Message;
import com.iqiyi.pps.epg.api.model.web.program.TProgram;
import com.iqiyi.pps.epg.core.model.channel.ChannelBase;
import com.iqiyi.pps.epg.core.model.channel.ChannelLog;
import com.iqiyi.pps.epg.core.model.control.IPlatformControl;
import com.iqiyi.pps.epg.core.model.stream.LiveChannelStream;
import com.iqiyi.pps.epg.core.model.stream.LiveStream;
import com.iqiyi.pps.epg.core.rpc.qipu.Composite.AlternatePlayCollectionImpl;
import com.iqiyi.pps.epg.core.rpc.qipu.Composite.NodeCommonImpl;
import com.iqiyi.pps.epg.core.rpc.qipu.Composite.NodeLiveChannelImpl;
import com.iqiyi.pps.epg.core.rpc.qipu.Composite.NodeLiveEpisodeImpl;
import com.iqiyi.pps.epg.core.rpc.qipu.QipuRequest;
import com.iqiyi.pps.epg.core.rpc.qipu.QipuService;
import com.iqiyi.pps.epg.core.service.broadcast.BroadcastControlService;
import com.iqiyi.pps.epg.core.service.channel.ChannelService;
import com.iqiyi.pps.epg.core.service.stream.LiveChannelStreamService;
import com.iqiyi.pps.epg.core.service.stream.LiveStreamService;
import com.iqiyi.pps.epg.core.utils.StreamOrderComparator;
import com.qiyi.knowledge.client.ServiceException;
import com.qiyi.knowledge.json.QipuJsonFormat;
import knowledge.pub.*;
import knowledge.pub.Properties;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: rainliang
 * Date: 13-08-25
 * Time: 下午11:50
 * 优化写奇谱增加重试
 */
@Service
public class QipuManager implements QipuService {
    //public final static int SYNC_CHANNEL_NUM = 200;
    private static final Logger logger = LoggerFactory.getLogger(QipuManager.class);

    @Autowired
    private QipuRequest qipuRequest;
    @Autowired
    private NodeLiveEpisodeImpl nodeLiveEpisodeImpl;
    @Autowired
    private NodeCommonImpl nodeCommonImpl;
    @Autowired
    private NodeLiveChannelImpl nodeLiveChannelImpl;
    @Autowired
    private LiveStreamService liveStreamService;
    @Autowired
    private LiveChannelStreamService liveChannelStreamService;
    @Autowired
    private ChannelService channelService;
    @Autowired
    private BroadcastControlService broadcastControlService;

    @Autowired
    private AlternatePlayCollectionImpl alternatePlayCollectionImpl;

    private static final Map<String, Integer> liveChannelStreamOrderMap = new HashMap<String, Integer>() {{
        put("HIGH_DEFINITION", 1);
//        put("TOP_SPEED", 2);
        put("SMOOTH", 3);
        put("RESOLUTION_720P", 4);
        put("RESOLUTION_1080P", 5);
        put("RESOLUTION_2K", 6);
        put("RESOLUTION_4K", 7);
    }};


    //----------------------------------------奇谱相关公共方法[BEGIN]---------------------//

    /**
     * 注册奇谱id
     *
     * @param type        Common.EntityIdType
     * @param total_count 奇谱id 个数，支持批量注册
     * @return
     */
    @Override
    public List<Long> registerQipuId(int type, int total_count) {
        long start = System.currentTimeMillis();
        List<Long> ret = nodeCommonImpl.registerQipuId(type, total_count);
        long end = System.currentTimeMillis();
        logger.info("[QipuManager][registerQipuId][type={}][total_count={}][time={}]", type, total_count, (end - start));
        return ret;
    }

    /**
     * 获取实体
     *
     * @param qipuId
     * @return
     */
    public Message getEntityByqipuId(Long qipuId) {
        return nodeCommonImpl.getEntityByqipuId(qipuId);
    }

    /**
     * 将奇谱的实体置为删除
     *
     * @param entityId
     * @param del
     * @return
     */
    public int setObjectDeletedToQipu(Long entityId, boolean del) {
        return nodeCommonImpl.setObjectDeletedToQipu(entityId, del);

    }

    //----------------------------------------奇谱相关公共方法[END]---------------------//

    //----------------------------------------写新奇谱频道信息[BEGIN]---------------------//

    /**
     * 写新奇谱直播频道结构live_channel_base信息
     *
     * @param entityId
     * @return
     */
    public int setLiveChannelBaseToQipu(Long entityId, ChannelBase channelBase) {
        logger.info("[QipuManager][setLiveChannelBaseToQipu][start][entityId={}][del={}]", entityId);

        if (entityId == null || entityId <= 0) {
            return -1;
        }

        Knowledge.LiveChannel.Builder liveChannelBuilder = nodeCommonImpl.newLiveChannelBuilder(entityId);

        // Construct a LiveChannelBase
        Properties.LiveChannelBase.Builder liveBase = Properties.LiveChannelBase.newBuilder();

        // 设置直播频道基本信息
        liveBase.setName(channelBase.getName()); // 频道名称
        liveBase.setShortName(channelBase.getShortName()); // 频道简称
        liveBase.setAbbrName(""); // 一个直播频道可能对应多个流名称，这里写不填写
        liveBase.setUniversalCode(channelBase.getUniversalCode()); // 直播频道代码（拉取节目单唯一标识）
        liveBase.setDescription(channelBase.getDescription()); // 频道描述
        liveBase.addPassportId(channelBase.getPassportId()); // 频道大V账号
        liveBase.setPpsBaikeId(channelBase.getPpsBaikeId()); // 频道PPS 百科ID
        liveBase.setLiveType(Common.LiveType.valueOf(channelBase.getLiveType())); // 直播类型
        liveBase.setType(Common.LiveChannelType.valueOf(channelBase.getType())); // 频道分类
        liveBase.setMaxPlaybackPeriod(channelBase.getMaxPlaybackPeriod()); // 支持最大回看时间
        liveBase.setOrder(channelBase.getOrderBy()); // 频道排序
        liveBase.setAllowPopups(channelBase.getAllowPopups() > 0 ? true : false);
        liveBase.setIsQiyiProduced(channelBase.getIsQiyiProduced() > 0 ? true : false); // 是否奇艺出品
        liveBase.setExclusiveStatusIqiyi(channelBase.getExclusiveStatusIqiyi() > 0 ? true : false); // 是否奇艺独播

        liveBase.setCarouselTableNo(channelBase.getCarouselTableNo()); // 轮播台台号

        List<Metadatas.MetaSummary> metaList = alternatePlayCollectionImpl.convertToMeta(channelBase.getAlternatePlayCollection());
        if (!metaList.isEmpty()) {
            liveBase.addAllAlternatePlayCollectionSummary(metaList);       //备播库
        }
        //  liveBase.setTvLiveCenterId(channelBase.getOldQipuId());     //频道18结尾直播ID


        if (channelBase.getEpisodeUpdateTime() != null) {
            liveBase.setEpisodeUpdateTime(channelBase.getEpisodeUpdateTime().getTime()); // 节目单最新更新时间
        }

        liveBase.setPlayerTips(channelService.getConfigData("InterruptType", channelBase.getInterruptHintType()).getDescr());
        // 设置频道别名
        if (StringUtils.isNotEmpty(channelBase.getTempName())) {
            Properties.LiveChannelBase.TempName.Builder tmpName = Properties.LiveChannelBase.TempName.newBuilder();

            tmpName.setAlias(channelBase.getTempName());
            tmpName.setStartTime(channelBase.getTempStartTime().getTime());
            tmpName.setEndTime(channelBase.getTempEndTime().getTime());
            liveBase.setTempName(tmpName);
        }

        // 设置频道地区信息
        Common.Location.Builder locatoin = Common.Location.newBuilder();
        locatoin.setCountry(channelBase.getLocation());
        //locatoin.setCountryId(48); // TODO 此次要根据上面地区名找到地区ID
        liveBase.setLocation(locatoin);

        Metadatas.MetaSummary.Builder metaSu = Metadatas.MetaSummary.newBuilder();
        metaSu.setEntityId(channelBase.getLogoEntityId());
        metaSu.setType(Metadatas.MetaSummary.Type.IMAGE_COVER);
        liveBase.setLogo(metaSu);
        liveChannelBuilder.setLiveChannelBase(liveBase);

        return nodeCommonImpl.writeEntity(liveChannelBuilder.build());
    }

    /**
     * 写新奇谱频道默认码流信息
     *
     * @param entityId
     * @return
     */
    public int setDefaultLiveStreamToQipu(Long entityId, LiveStream liveStreamData) {
        logger.info("[QipuManager][setDefaultLiveStreamToQipu][start][entityId={}][del={}]", entityId);
        logger.info("[QipuManager][setDefaultLiveStreamToQipu][LiveSteam][{}]", JSON.toJSONString(liveStreamData));
        if (entityId == null || entityId <= 0) {
            return -1;
        }

        return 0;
//        Knowledge.LiveChannel.Builder liveChannelBuilder = nodeCommonImpl.newLiveChannelBuilder(entityId);
//        liveChannelBuilder.setDefaultLiveStream(nodeLiveChannelImpl.getLiveStreamData(liveStreamData, null));
//        return nodeCommonImpl.writeEntity(liveChannelBuilder.build());
    }

    /**
     * 删除新奇谱频道流信息列表
     *
     * @param entityId
     * @return
     */
    public int delLiveStreamToQipu(Long entityId, String uuid) {
        logger.info("[QipuManager][delLiveStreamToQipu][start][entityId={}][uuid={}]", entityId, uuid);
        if (entityId == null || entityId <= 0) {
            return -1;
        }

        setNewDefaultLiveStreamToQipu(entityId);

        Knowledge.LiveChannel.Builder builder = nodeCommonImpl.newLiveChannelBuilder(entityId);
        Properties.LiveStream.Builder liveStreamBuilder = Properties.LiveStream.newBuilder();
        liveStreamBuilder.setUuid(uuid);
        builder.addLiveStream(liveStreamBuilder);
        return nodeCommonImpl.deleteEntity(builder.build());
    }

    /**
     * 添加新奇谱频道流信息列表
     *
     * @param entityId
     * @return
     */
    public int addLiveStreamToQipu(Long entityId, LiveStream liveStreamData) {
        logger.info("[QipuManager][addLiveStreamToQipu][start][entityId={}][liveStreamData={}]",
                entityId, JSON.toJSONString(liveStreamData));
        if (entityId == null || entityId <= 0 || liveStreamData == null) {
            return -1;
        }

        if (liveStreamData.getFormatType().equals(LiveStream.FORMATTYPE_FLV)) {
            setNewDefaultLiveStreamToQipu(entityId);
        }

        Knowledge.LiveChannel.Builder liveChannelBuilder = nodeCommonImpl.newLiveChannelBuilder(entityId);
        liveChannelBuilder.addLiveStream(nodeLiveChannelImpl.getLiveStreamData(liveStreamData, null));
        return nodeCommonImpl.writeEntity(liveChannelBuilder.build());
    }

    public int updateLiveStreamsToQipu(long qipuId, List<LiveStream> addList, List<String> delList, LiveStream defaultStream) {
        logger.info("[QipuManager][updateLiveStreamsToQipu][start][entityId={}][addList={}]][delList={}]",
                qipuId, JSON.toJSONString(addList), JSON.toJSON(delList));

//        logger.info("[QipuManager][updateLiveStreamsToQipu][start][entityId={}]", qipuId);

        if (addList.size() == 0 && delList.size() == 0) {
            logger.info("[QipuManager][updateLiveStreamsToQipu][addList and delList are empty]");
            return 0;
        }

        Knowledge.LiveChannel.Builder liveChannelBuilder = nodeCommonImpl.newLiveChannelBuilder(qipuId);
        for (LiveStream liveStream : addList) {
            if (liveStream != null) {
                liveChannelBuilder.addLiveStream(nodeLiveChannelImpl.getLiveStreamData(liveStream, null));
            }
        }

        setNewDefaultLiveStreamToQipu(qipuId);

        Knowledge.LiveChannel.Builder delBuilder = nodeCommonImpl.newLiveChannelBuilder(qipuId);
        for (String uuid : delList) {
            delBuilder.addLiveStream(Properties.LiveStream.newBuilder().setUuid(uuid));
        }
        return nodeCommonImpl.setEntity(liveChannelBuilder.build(), delBuilder.build());
    }

    /**
     * 写图片奇谱信息（兼容老版本）
     *
     * @param channelBase
     * @return
     */
    public int setImageDataToQipu(ChannelBase channelBase) {
        Long entityId = channelBase.getLogoEntityId();
        String urlString = channelBase.getDefaultLogoUrl();
        logger.info("[QipuManager][setImageDataToQipu][start][entityId={}][url={}]", entityId, urlString);
        if (entityId == null || entityId <= 0) {
            return -1;
        }
        if (urlString == null) {
            return 0;
        }
        Knowledge.Image.Builder imageData = Knowledge.Image.newBuilder();
        imageData.setId(entityId);

        Metadatas.ImageMetadata.Builder imageMetadataBuiler = Metadatas.ImageMetadata.newBuilder();
        imageMetadataBuiler.setEntityId(entityId);
        imageMetadataBuiler.setType(Metadatas.ImageMetadata.Type.POSTER);
        imageMetadataBuiler.setDescription(channelBase.getDescription());
        imageData.setMetadata(imageMetadataBuiler);
        // 写image_format之前先清空
        Knowledge.Image qipuImageData = (Knowledge.Image) nodeCommonImpl.getEntityByqipuId(entityId);
        Knowledge.Image.Builder delBuilder = null;
        if (qipuImageData == null) {
            logger.info("[QipuManager][qipuImageData is null][entityId={}]", entityId);
        } else if (qipuImageData.getImageFormatCount() > 0) {
            delBuilder = Knowledge.Image.newBuilder();
            delBuilder.setId(entityId);
            delBuilder.addAllImageFormat(qipuImageData.getImageFormatList());
        }

        // 写format
        String url = urlString.substring(0, urlString.lastIndexOf(".")) + "_64_64" + urlString.substring(urlString.lastIndexOf("."));
        if (url != null) {
            Formats.ImageFormat.Builder imageFormatBuilder = Formats.ImageFormat.newBuilder();
            imageFormatBuilder.setFormat(url.substring(url.lastIndexOf(".") + 1));
            imageFormatBuilder.setUuid(UUID.randomUUID().toString());
            imageFormatBuilder.setWidth(65);
            imageFormatBuilder.setHeight(50);
            imageFormatBuilder.setUrl(url);
            imageData.addImageFormat(imageFormatBuilder);
        }
        if (delBuilder == null) {
            return nodeCommonImpl.writeEntity(imageData.build());
        } else {
            return nodeCommonImpl.setEntity(imageData.build(), delBuilder.build());
        }
    }


    public boolean addAccessPlayControlToQipu(long entityId, boolean searchForbidden, List<? extends IPlatformControl> platformControlList) {
        logger.info("[QipuManager][addAccessPlayControlToQipu][start][entityId={}][platformControlList size={}]",
                entityId, platformControlList.size());

        try {
            if (entityId < 1) {
                return false;
            }
            if (platformControlList == null || platformControlList.size() == 0) {
                logger.info("[entityId={}] platformControlList empty skip", entityId);
                return true;
            }
            int rest = (int) (entityId % 100);
            Knowledge.LiveChannel.Builder addBuilder1 = null;
            Knowledge.LiveEpisode.Builder addBuilder2 = null;
            if (rest == 22) {
                addBuilder1 = nodeCommonImpl.newLiveChannelBuilder(entityId);
            } else if (rest == 23) {
                addBuilder2 = nodeCommonImpl.newLiveEpisodeBuilder(entityId);
            }
            // 设置平台以及平台下的地区黑名单
            for (IPlatformControl platformItem : platformControlList) {
                Properties.AccessPlayControl.Builder playControl = Properties.AccessPlayControl.newBuilder();
                playControl.setPlayPlatform(Common.PlayPlatform.valueOf(platformItem.getPlayPlatform()));
                // 设置该平台播控信息

                Properties.AccessPlayControl.Control.Builder defaultControl = Properties.AccessPlayControl.Control.newBuilder();
                defaultControl.setIsDownloadAllowed(true);
                defaultControl.setIsDrm(false);
                defaultControl.setIsShareAllowed(true);
                defaultControl.setIsCooperationAllowed(true);
                defaultControl.setRejectRecommend(false);
                defaultControl.setRejectTop(false);
                defaultControl.setLiveDelayTime(platformItem.getLiveDelayTime());
                if (searchForbidden) {
                    defaultControl.setRejectSearch(true);
                } else {
                    defaultControl.setRejectSearch(platformItem.getRejectSearch() == 0 ? false : true);
                }
                if (platformItem.getAvailableStatus() == 1) {
                    defaultControl.setAvailabeStatus(Common.AvailableStatus.ONLINE);
                } else {
                    defaultControl.setAvailabeStatus(Common.AvailableStatus.OFFLINE_COPYRIGHT);
                }
                playControl.setDefaultControl(defaultControl);
                playControl.clearRegionControl(); // 清除地区黑名单
                // 设置地区黑名单
                if (StringUtils.isNotEmpty(platformItem.getBlacklist())) {
                    Properties.AccessPlayControl.RegionControl.Builder regionControl = Properties.AccessPlayControl.RegionControl.newBuilder();

                    String[] locations = platformItem.getBlacklist().split(",");
                    for (String item : locations) {
                        // 3_95_香港 1：洲；2：国家：3省：4市；5县；6 area
                        String[] locationInfo = item.split("_");
                        if (locationInfo.length != 3) {
                            continue;
                        }
                        Common.Location.Builder location = Common.Location.newBuilder();
                        fillLocaltionInfo(locationInfo, location);
                        if (location.getAreaId() == 301) {
                            location.setAreaSpell("oversea");
                            Common.Location.Builder newLocation = Common.Location.newBuilder();
                            newLocation.setCountryId(301);
                            newLocation.setCountry(locationInfo[2]);
                            regionControl.addLocation(newLocation);
                        }
                        regionControl.addLocation(location);
                        // 海外 特殊处理
                    }

                    // 设置黑名单信息
                    Properties.AccessPlayControl.Control.Builder locationControl = getAccessPlayControl(platformItem, searchForbidden);
                    regionControl.setLocationControl(locationControl);
                    playControl.addRegionControl(regionControl);
                }
                if (addBuilder1 != null) {
                    addBuilder1.addAccessPlayControl(playControl);
                }
                if (addBuilder2 != null) {
                    addBuilder2.addAccessPlayControl(playControl);
                }

            }
            int result = -1;
            if (addBuilder1 != null) {
                result = nodeCommonImpl.writeEntity(addBuilder1.build());
            }
            if (addBuilder2 != null) {
                result = nodeCommonImpl.writeEntity(addBuilder2.build());
            }
            return result == Common.RpcStatus.OK_VALUE ? true : false;
        } catch (Exception e) {
            logger.error("[QipuManager][addAccessPlayControlToQipu][exception=]", e);
            return false;
        }

    }

    private void fillLocaltionInfo(String[] locationInfo, Common.Location.Builder location) {
        switch (locationInfo[0]) {
            case "1":
                location.setContinent(locationInfo[2]);
                location.setContinentId(Integer.valueOf(locationInfo[1]));
                break;
            case "2":
                location.setCountry(locationInfo[2]);
                location.setCountryId(Integer.valueOf(locationInfo[1]));
                break;
            case "3":
                location.setProvince(locationInfo[2]);
                location.setProvinceId(Integer.valueOf(locationInfo[1]));
                break;
            case "4":
                location.setCity(locationInfo[2]);
                location.setCityId(Integer.valueOf(locationInfo[1]));
                break;
            case "5":
                location.setRegion(locationInfo[2]);
                location.setRegionId(Integer.valueOf(locationInfo[1]));
                break;
            case "6":
                location.setArea(locationInfo[2]);
                location.setAreaId(Integer.valueOf(locationInfo[1]));
                break;
        }
    }

    private Properties.AccessPlayControl.Control.Builder getAccessPlayControl(IPlatformControl platformItem, boolean searchForbidden) {
        Properties.AccessPlayControl.Control.Builder locationControl = Properties.AccessPlayControl.Control.newBuilder();
        locationControl.setIsDownloadAllowed(true);
        locationControl.setIsDrm(false);
        locationControl.setIsShareAllowed(true);
        locationControl.setIsCooperationAllowed(true);
        locationControl.setRejectRecommend(false);
        locationControl.setRejectTop(false);
        if (searchForbidden) {
            locationControl.setRejectSearch(true);
        } else {
            locationControl.setRejectSearch(platformItem.getRegionRejectSearch() == 0 ? false : true);
        }
        locationControl.setAvailabeStatus(Common.AvailableStatus.OFFLINE_COPYRIGHT);
        return locationControl;
    }

    //----------------------------------------写新奇谱节目单信息[BEGIN]---------------------//

    public void syncProgramDataList(boolean syncFlag) {
        nodeLiveEpisodeImpl.syncProgramDataList(syncFlag);
    }

    public void syncProgramData(TProgram tProgram, boolean syncFlag) {
        nodeLiveEpisodeImpl.syncProgramData(tProgram, syncFlag);
    }

    public void syncProgramDataByFatherId(long fatherId) {
        nodeLiveEpisodeImpl.forceSyncProgramDataList(fatherId);
    }
    //----------------------------------------写新奇谱节目单信息[END]---------------------//


    //----------------------------------------写老奇谱结构频道信息[BEGIN]---------------------//


    //----------------------------------------同步频道信息到奇谱[BEGIN]---------------------//
    public void syncSingleChannelToQipu(ChannelBase channelBase) {
        try {
            logger.info("[syncSingleChannelToQipu] start sync [channelId={}]", channelBase.getId());
            // 判断是否有新老奇谱ID
            if (channelBase.getQipuId() <= 0) {
                List<Long> qipuIdList = this.registerQipuId(22, 1);
                channelBase.setQipuId(qipuIdList.get(0));
            }
            Map<String, String> logMap = new HashMap();
            int writeToqipuRes = nodeLiveChannelImpl.syncChannelDataListToNewQipu(channelBase);
            if (writeToqipuRes < 0) {
                logMap.put("writeLiveChannelToQipu", "false");
            } else {
                logMap.put("writeLiveChannelToQipu", "true");
            }
            //  this.syncChannelDataListToOldQipu(channelBase);  同步到老奇谱结构
            int imageDataRes = this.setImageDataToQipu(channelBase); // 同步频道LOGO到奇谱
            if (imageDataRes < 0) {
                logMap.put("setImageDataToQipu", "false");
            } else {
                logMap.put("setImageDataToQipu", "true");
            }

            // 同步频道播控信息到新老奇谱(此方法中已考虑到预约上下线情况)
            boolean res = broadcastControlService.writeQipuBroadcast(channelBase);
            if (res) {
                logMap.put("writeQipuBroadcast", "true");
            } else {
                logMap.put("writeQipuBroadcast", "false");
            }
            boolean syncOver = writeToqipuRes > -1 && imageDataRes > -1 && res;
            channelBase.setIsSync(syncOver ? 0 : 1); // 修改奇谱同步状态
            channelService.saveBase(channelBase);

            logMap.put("update sync result ", syncOver + "");
            String strLog = net.sf.json.JSONObject.fromObject(logMap).toString();
            this.saveChannelLog(channelBase.getId(), strLog);
        } catch (Exception e) {
            logger.error("[syncSingleChannelToQipu] [channelId=" + channelBase.getId(), e);
        }

    }

    /**
     * 从 channel_base 表中取出需要同步的频道列表，逐个写频道信息到奇谱
     */
    public void syncChannelDataList() {
        logger.info("[QipuManager][syncChannelDataList][start]");

        try {
            // 获取需要同步的频道列表
            List<ChannelBase> channelBaseList = channelService.getChannelBaseList(1);
            if (channelBaseList != null && channelBaseList.size() > 0) {
                Integer syncNum = 0;
                for (ChannelBase channelBase : channelBaseList) {
                    this.syncSingleChannelToQipu(channelBase);
//                    syncNum++;
//                    if (syncNum >= SYNC_CHANNEL_NUM) break; // 一次只同步指定条数据的频道数据
                }
            } else {
                logger.info("[QipuManager][syncChannelDataList][noSyncData]");
            }
        } catch (Exception e) {
            logger.info("[QipuManager][syncChannelDataList][error]{}", e);
        }
        logger.info("[QipuManager][syncChannelDataList][end]");
    }

    // 记录频道操作日志
    private void saveChannelLog(Long fatherId, String descr) {
        ChannelLog channelLog = new ChannelLog();
        channelLog.setFatherId(fatherId);
        channelLog.setType(103);
        channelLog.setUser("system");
        channelLog.setDescr(descr);

        channelService.saveLog(channelLog);

        logger.info("[QipuManager][saveChannelLog][fatherId={}][descr={}]", fatherId, descr);
    }

    public int setLiveEpisodeFatherInfoToQipu(Long entityId, TProgram tProgram, long fQipuId, boolean isValid) {
        logger.info("[QipuManager][setLiveEpisodeFatherInfoToQipu][start][entityId={}][del={}]", entityId);
        if (entityId == null || entityId <= 0) {
            return -1;
        }

        return nodeLiveEpisodeImpl.setLiveEpisodeFatherInfoToQipu(entityId, tProgram, isValid, fQipuId);
    }

    /**
     * 新奇谱的platform转换成老奇谱的platform
     *
     * @param key
     * @return
     */
    public static Common.DistributionPlatform newPlatform2OldPlatform(int key) {
        switch (key) {
            case 1:
                return Common.DistributionPlatform.PC_APP_PPS;
            case 2:
            case 4:
            case 5:
            case 6:
            case 18: //PlayPlatform ANDROID_PAD_PPS_VALUE
                return Common.DistributionPlatform.PHONE_APP_PPS;
            case 14:
                return Common.DistributionPlatform.PC_IQIYI;
            case 17:
                return Common.DistributionPlatform.PC_APP_IQIYI;
            case 10:
            case 12:
                return Common.DistributionPlatform.PHONE_APP_IQIYI;
            case 13:
            case 11:
                return Common.DistributionPlatform.PAD_APP_IQIYI;
            case 15:
                return Common.DistributionPlatform.PHONE_WEB_IQIYI;
            case 9:
                return Common.DistributionPlatform.IPTV_IQIYI;
        }
        return null;
    }

    public int setNewDefaultLiveStreamToQipu(Long channelqipuId) {
        logger.info("[QipuManager][setNewDefaultLiveStream][start][channelqipuId={}]", channelqipuId);

        if (channelqipuId == null || channelqipuId <= 0) {
            return -1;
        }

        ChannelBase channelBase = channelService.getChannelByQipuId(channelqipuId);

        if (null == channelBase) {
            logger.info("[QipuManager][setNewDefaultLiveStream][channelqipuid={}] channel not exists", channelqipuId);
            return -1;
        }

        long channelId = channelBase.getId();

        List<LiveChannelStream> liveChannelStreamList = liveChannelStreamService.getByIsEnable(channelId, true);

        if (null == liveChannelStreamList || liveChannelStreamList.size() < 1) {
            logger.info("[QipuManager][setNewDefaultLiveStream] have no enabled livechannelstream");
            return 0;
        }

        if (liveChannelStreamList.size() > 1) {
            Collections.sort(liveChannelStreamList, new StreamOrderComparator(liveChannelStreamOrderMap));
        }

        for (LiveChannelStream liveChannelStream : liveChannelStreamList) {
            LiveStream defaultLiveStream = liveStreamService.get(channelId, liveChannelStream.getStreamName(), LiveStream.FORMATTYPE_FLV);

            if (defaultLiveStream != null) {
                Knowledge.LiveChannel.Builder liveChannelBuilder = nodeCommonImpl.newLiveChannelBuilder(channelqipuId);
                liveChannelBuilder.setDefaultLiveStream(nodeLiveChannelImpl.getLiveStreamData(defaultLiveStream, liveChannelStream));
                return nodeCommonImpl.writeEntity(liveChannelBuilder.build());
            }
        }

        return 0;
    }

    public LiveStream getDefaultLiveStreamByChannel(Long channelqipuId) {

        if (channelqipuId == null || channelqipuId <= 0) {
            return null;
        }

        ChannelBase channelBase = channelService.getChannelByQipuId(channelqipuId);

        if (null == channelBase) {
            logger.info("[QipuManager][setNewDefaultLiveStream][channelqipuid={}] channel not exists", channelqipuId);
            return null;
        }

        long channelId = channelBase.getId();

        List<LiveChannelStream> liveChannelStreamList = liveChannelStreamService.getByIsEnable(channelId, true);

        if (null == liveChannelStreamList || liveChannelStreamList.size() < 1) {
            logger.info("[QipuManager][setNewDefaultLiveStream] have no enabled livechannelstream");
            return null;
        }

        if (liveChannelStreamList.size() > 1) {
            Collections.sort(liveChannelStreamList, new StreamOrderComparator(liveChannelStreamOrderMap));
        }

        for (LiveChannelStream liveChannelStream : liveChannelStreamList) {
            LiveStream defaultLiveStream = liveStreamService.get(channelId, liveChannelStream.getStreamName(), LiveStream.FORMATTYPE_FLV);

            if (defaultLiveStream != null) {
                return defaultLiveStream;
            }
        }

        return null;
    }

    public String getQipuEntityData(Long qipuId) {
        long start = System.currentTimeMillis();
        logger.info("[getQipuEntityData][qipuId={}]", qipuId);
        String jsonString = null;
        try {
            ReadService.GetEntityResponse response = qipuRequest.getFusionService().getEntity(Arrays.asList(qipuId));
            if (response.getRpcStatusInfo().getRpcStatus() == Common.RpcStatus.OK) {
                String qs = String.valueOf(qipuId);
                if (qs.endsWith("00")) {
                    if (response.getEpisodeCount() > 0) {
                        Knowledge.Episode episode = response.getEpisode(0);
                        jsonString = QipuJsonFormat.printToString(episode);
                    }
                } else if (qs.endsWith("01")) {
                    if (response.getAlbumCount() > 0) {
                        Knowledge.Album album = response.getAlbum(0);
                        jsonString = QipuJsonFormat.printToString(album);
                    }
                }  else if (qs.endsWith("02")) {
                    if (response.getCollectionCount()  > 0) {
                        Knowledge.Collection collection = response.getCollection(0);
                        jsonString = QipuJsonFormat.printToString(collection);
                    }
                }else if (qs.endsWith("22")) {
                    if (response.getLiveChannelCount() > 0) {
                        Knowledge.LiveChannel liveChannel = response.getLiveChannel(0);
                        jsonString = QipuJsonFormat.printToString(liveChannel);
                    }
                } else if (qs.endsWith("23")) {
                    if (response.getLiveEpisodeCount() > 0) {
                        Knowledge.LiveEpisode liveEpisode = response.getLiveEpisode(0);
                        jsonString = QipuJsonFormat.printToString(liveEpisode);
                    }
                }
            }
            logger.info("[getQipuEntityData][qipuId={}][cost={}]", qipuId, System.currentTimeMillis() - start);
        } catch (ServiceException e) {
            logger.error("[getQipuEntityData]", e);
            return null;
        }
        return jsonString;
    }
}